import { Middleware, MiddlewareContext } from '../../core/types';

export interface Metric {
  name: string;
  value: number;
  url?: string;
  method?: string;
  status?: number;
}

export interface MetricsOptions {
  track?: (metric: Metric) => void;
}

export function metrics(options: MetricsOptions = {}): Middleware {
  const {
    track = (metric) =>
      console.log(`[Metrics] ${metric.name}: ${metric.value}ms`),
  } = options;

  return async (ctx: MiddlewareContext, next) => {
    const start = performance.now();

    try {
      await next();
    } finally {
      const duration = performance.now() - start;

      track({
        name: 'request_duration',
        value: duration,
        url: ctx.config.url,
        method: ctx.config.method,
        status: ctx.response?.status,
      });
    }
  };
}
